package com.pink.utils;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.pink.component.RedisComponent;
import com.pink.entity.enums.ResponseCodeEnum;
import com.pink.entity.vo.RestBeanVo;
import com.pink.entity.vo.response.CaptchaVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class CodeUtils {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Resource
    RedisComponent redisComponent;

    @Resource
    private DefaultKaptcha kaptcha;

    public CaptchaVo getCaptcha(){
        try {
            // 生成验证码文本
            String captchaText = kaptcha.createText();

            // 生成CheckCodeKey
            String checkCodeKey = UUID.randomUUID().toString();

            // 使用Redis存储验证码文本，设置3分钟有效期
            redisComponent.saveCheckCode(checkCodeKey, captchaText);
            // 生成验证码图片
            BufferedImage captchaImage = kaptcha.createImage(captchaText);

            // 将验证码图片转换为PNG格式的byte数组
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(captchaImage, "png", baos);
            byte[] pngImageBytes = baos.toByteArray();

            // 对byte数组进行Base64编码
            String base64Image = Base64.getEncoder().encodeToString(pngImageBytes);

            log.info("验证码图片宽度: {}, 高度: {}", captchaImage.getWidth(), captchaImage.getHeight());
            log.info("Base64编码后的图片长度: {}", base64Image.length());

            CaptchaVo captchaVo = new CaptchaVo();
            captchaVo.setCheckCode("data:image/png;base64," + base64Image);
            captchaVo.setCheckCodeKey(checkCodeKey);

            // 将验证码图片写入响应输出流
            return captchaVo;
        }catch (Exception e){
            log.error("生成验证码失败", e);
            throw new RuntimeException(ResponseCodeEnum.CODE_500.getMessage());
        }
    }

    public String getCode(String codeKey) {
        String code =  stringRedisTemplate.opsForValue().get(codeKey);
        stringRedisTemplate.delete(codeKey);
        return code;
    }
}
